package cn.iocoder.springboot.lab72.jdbc.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.ParameterMapper;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.sql.DataSource;
import java.util.List;
import java.util.Map;

@Component
public class ProcedureTemplate {


    private static DataSource dataSource;

    @Autowired
    private ProcedureTemplate(DataSource dataSource) {
        ProcedureTemplate.dataSource = dataSource;
    }

    private static StoredProcedure getProcedureTemplate(String procedureName, List<SqlParameter> sqlParameters) {
        StoredProcedure storedProcedure = new StoredProcedure() {
        };
        storedProcedure.setDataSource(dataSource);
        storedProcedure.setSql(procedureName);
        if (!CollectionUtils.isEmpty(sqlParameters)) {
            for (SqlParameter sqlParameter : sqlParameters) {
                storedProcedure.declareParameter(sqlParameter);
            }
        }
        storedProcedure.compile();
        System.out.println("存储过程调用========" + storedProcedure.getCallString());
        storedProcedure.getJdbcTemplate().execute("set behavior_compat_options=block_return_multi_results");
        return storedProcedure;
    }

    public static Map<String, Object> execute(String procedureName, List<SqlParameter> sqlParameters) {
        StoredProcedure procedureTemplate = getProcedureTemplate(procedureName, sqlParameters);
        return procedureTemplate.execute();
    }

    public static Map<String, Object> execute(String procedureName, List<SqlParameter> sqlParameters, Object... inParams) {
        StoredProcedure procedureTemplate = getProcedureTemplate(procedureName, sqlParameters);
        return procedureTemplate.execute(inParams);
    }

    public static Map<String, Object> execute(String procedureName, List<SqlParameter> sqlParameters, Map<String, Object> params) {
        StoredProcedure procedureTemplate = getProcedureTemplate(procedureName, sqlParameters);
        return procedureTemplate.execute(params);
    }

    public static Map<String, Object> execute(String procedureName, List<SqlParameter> sqlParameters, ParameterMapper inParamMapper) {
        StoredProcedure procedureTemplate = getProcedureTemplate(procedureName, sqlParameters);
        return procedureTemplate.execute(inParamMapper);
    }
}
